package Q495;

import java.util.HashSet;

/**
 * 每日一题：提莫攻击
 *
 * @author 23737
 * @time 2021.11.10
 */
public class Test {
    public static void main(String[] args) {
        System.out.println(new Solution().findPoisonedDuration(new int[]{1, 4}, 2));
        System.out.println(new Solution().findPoisonedDuration2(new int[]{1, 4}, 2));
    }
}

class Solution {
    //自己写的解法 只能过一半的样例
    public int findPoisonedDuration(int[] timeSeries, int duration) {
        if (timeSeries.length == 1) {
            return duration;
        }
        HashSet<Integer> set = new HashSet<>();
        int count = 0, sum = 0;
        int[] check = new int[2];
        for (int i = 0; i < timeSeries.length; i++) {
            if (i == timeSeries.length - 1) {
                return sum;
            }
            check[0] = timeSeries[i];
            check[1] = timeSeries[i + 1];
            for (int j = check[0]; j <= check[0] + duration - 1; j++) {
                set.add(j);
                count++;
                if (set.contains(check[1])) {
                    count = j + duration - 1;
                    sum = count;
                    break;
                } else {
                    sum = timeSeries.length * duration;
                }
            }
        }
        return sum;
    }

    //松哥的解法
    public int findPoisonedDuration2(int[] timeSeries, int duration) {
        //首先定义res，并且赋值为中毒时间
        int res = duration;
        //定义右边界为数组的第一位加时长-1
        int right = timeSeries[0] + duration - 1;
        //开始循环了，这里注意i是1开始
        for (int i = 1; i < timeSeries.length; i++) {
            //如果数组的第二个数大于右边界 说明中毒后再进行射击的，res加上时长，并把右边界重置为第二个数的时长-1
            if (timeSeries[i] > right) {
                res += duration;
                right = timeSeries[i] + duration - 1;
                continue;
            }
            //没进入if语句 说明第i次的射击实在[timeSeries[0],timeSeries[0]+duration-1]这个区间的
            //res加上前边的中毒时长，再将右边界设置为timeSeries[i] + duration - 1
            res += timeSeries[i] - timeSeries[i - 1];
            right = timeSeries[i] + duration - 1;
        }
//        res += duration;
        return res;
    }

}
